package com.zyl.demo.controller;

import com.fasterxml.jackson.core.JsonEncoding;
import com.zyl.demo.beans.*;
import com.zyl.demo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RestController
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    CategorySubService categorySubService;

    @Autowired
    CommodityService commodityService;

    @Autowired
    HomeService homeService;
    @Autowired
    AdBeanService adBeanService;

    @Autowired
    ShopInfoService shopInfoService;

    @GetMapping("/getC")
    @ResponseBody
    public BaseBean getHttpC() {
        BaseBean baseBean = new BaseBean(categoryService.getAllCategory());
        return baseBean;
    }

    @PostMapping("/getHomePage")
    @ResponseBody
    public BaseBean getHomePage() {
        HomePageBean homePageBean = new HomePageBean();

        List<Home> allHome = homeService.getAllHome();
        List<Commodity> homeCommoditys = new ArrayList<>();
        allHome.forEach(v -> {
            homeCommoditys.add(commodityService.getCommodityById(v.getCommodityId()));
        });

        homePageBean.setCommodityList(homeCommoditys);
        homePageBean.setCategoryList(categoryService.getAllCategory());
        homePageBean.setAdBean(adBeanService.getAdBean());
        homePageBean.setShopInfo(shopInfoService.getShopInfo());
        homePageBean.setRecommendList(commodityService.getRecommendList());
        //楼层
        List<Category> categoryTopThree = categoryService.getCategoryTopThree();
        homePageBean.setFloorCategoryList(categoryTopThree);

        homePageBean.setFloorCommodityListOne(commodityService.getCommodityByCategoryIdFive(categoryTopThree.get(0).getCategoryId()));
        homePageBean.setFloorCommodityListTow(commodityService.getCommodityByCategoryIdFive(categoryTopThree.get(1).getCategoryId()));
        homePageBean.setFloorCommodityListThree(commodityService.getCommodityByCategoryIdFive(categoryTopThree.get(2).getCategoryId()));

        return new BaseBean(homePageBean);
    }



    @PostMapping("/getCommodity")
    @ResponseBody
    public BaseBean getCommodity() {
        BaseBean baseBean = new BaseBean(commodityService.getAllCommodity());
        return baseBean;
    }

    @PostMapping("/getCategory")
    @ResponseBody
    public BaseBean getCategory() {
        List<Category> allCategory = categoryService.getAllCategory();
        allCategory.forEach(c->{
            List<CategorySub> categorySubByCategoryId = new ArrayList<>();
            CategorySub categorySub = new CategorySub();
            categorySub.setCategoryId(c.getCategoryId());
            categorySub.setCategorySubId(-1);
            categorySub.setCategorySubName("全部");
            categorySubByCategoryId.add(categorySub);

            categorySubByCategoryId.addAll(categorySubService.getCategorySubByCategoryId(c.getCategoryId()));
            c.setCategorySubList(categorySubByCategoryId);
        });
        BaseBean baseBean = new BaseBean(allCategory);
        return baseBean;
    }

    @PostMapping("/getCategorySub")
    @ResponseBody
    public BaseBean getCategorySub() {
        BaseBean baseBean = new BaseBean(categorySubService.getAllCategorySub());
        return baseBean;
    }

    @PostMapping("/getHome")
    @ResponseBody
    public BaseBean getHome() {
        BaseBean baseBean = new BaseBean(homeService.getAllHome());
        return baseBean;
    }


    @PostMapping("/uploadCategory")
    public String uploadCategory(@RequestParam("file") MultipartFile multipartFile, Category category) {
        //获取static目录 获取static就可以完成上传功能了
        String realPath = "";
        try {
            realPath = ResourceUtils.getURL("classpath:").getPath() + "static";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String path = "/category/img/";
        String fileName = "";
        File file = new File(realPath + path);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
            fileName = System.currentTimeMillis() + ".png";
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file.getPath() + File.separator + fileName));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, len);
            }
            inputStream.close();
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        category.setCategoryImg(path + fileName);
        categoryService.addCategory(category);
        return "上传成功";
    }


    @PostMapping("/uploadCategorySub")
    public String uploadCategorySub(@RequestParam("file") MultipartFile multipartFile, CategorySub categorySub) {
        //获取static目录 获取static就可以完成上传功能了
        String realPath = "";
        try {
            realPath = ResourceUtils.getURL("classpath:").getPath() + "static";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String path = "/category/img/" + categorySub.getCategoryId() + "/";
        String fileName = "";
        File file = new File(realPath + path);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
            fileName = System.currentTimeMillis() + ".png";
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file.getPath() + File.separator + fileName));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, len);
            }
            inputStream.close();
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        categorySub.setCategorySubImg(path + fileName);
        categorySubService.addCategory(categorySub);
        return "上传成功Sub";
    }

    @PostMapping("/uploadCommodity")
    public String uploadCommodity(@RequestParam("commodityImgSmallFile") MultipartFile commodityImgSmallFile,
                                  @RequestParam("commodityImgMediumFile") MultipartFile commodityImgMediumFile,
                                  @RequestParam("commodityImgBigFile") MultipartFile commodityImgBigFile,
                                  @RequestParam("commodityImg1File") MultipartFile commodityImg1File,
                                  @RequestParam("commodityImg2File") MultipartFile commodityImg2File,
                                  @RequestParam("commodityImg3File") MultipartFile commodityImg3File,
                                  @RequestParam("commodityImg4File") MultipartFile commodityImg4File,
                                  @RequestParam("commodityImgDetails1File") MultipartFile commodityImgDetails1File,
                                  @RequestParam("commodityImgDetails2File") MultipartFile commodityImgDetails2File,
                                  @RequestParam("commodityImgDetails3File") MultipartFile commodityImgDetails3File,
                                  @RequestParam("commodityImgDetails4File") MultipartFile commodityImgDetails4File,
                                  Commodity commodity) {
        //获取static目录 获取static就可以完成上传功能了
        String realPath = "";
        try {
            realPath = ResourceUtils.getURL("classpath:").getPath() + "static";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String path = "/category/img/" + commodity.getCategoryId() + "/" + commodity.getCategorySubId() + "/";
        String pathShow = path + "show/";
        String pathCarousel = path + "carousel/";
        String pathDetails = path + "details/";
        File fileShow = new File(realPath + pathShow);
        File fileCarousel = new File(realPath + pathCarousel);
        File fileDetails = new File(realPath + pathDetails);
        if (!fileShow.exists()) {
            fileShow.mkdirs();
        }
        if (!fileCarousel.exists()) {
            fileCarousel.mkdirs();
        }
        if (!fileDetails.exists()) {
            fileDetails.mkdirs();
        }

        commodity.setCommodityImg(writeFileImage(commodityImgSmallFile, fileShow, pathShow));
        commodity.setCommodityImgMedium(writeFileImage(commodityImgMediumFile, fileShow, pathShow));
        commodity.setCommodityImgBig(writeFileImage(commodityImgBigFile, fileShow, pathShow));

        commodity.setCommodityImg1(writeFileImage(commodityImg1File, fileCarousel, pathCarousel));
        commodity.setCommodityImg2(writeFileImage(commodityImg2File, fileCarousel, pathCarousel));
        commodity.setCommodityImg3(writeFileImage(commodityImg3File, fileCarousel, pathCarousel));
        commodity.setCommodityImg4(writeFileImage(commodityImg4File, fileCarousel, pathCarousel));

        commodity.setCommodityImgDetails1(writeFileImage(commodityImgDetails1File, fileDetails, pathDetails));
        commodity.setCommodityImgDetails2(writeFileImage(commodityImgDetails2File, fileDetails, pathDetails));
        commodity.setCommodityImgDetails3(writeFileImage(commodityImgDetails3File, fileDetails, pathDetails));
        commodity.setCommodityImgDetails4(writeFileImage(commodityImgDetails4File, fileDetails, pathDetails));

//        commodityService.addCommodity(commodity);
        return "上传成功commodity";
    }

    public String writeFileImage(MultipartFile multipartFile, File file, String path) {
        String fileName = "";

        try {
            if (multipartFile.getInputStream()==null){
                return "";
            }
            System.out.println(path);
            FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
            fileName = System.currentTimeMillis() + ".png";
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file.getPath() + File.separator + fileName));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, len);
            }
            inputStream.close();
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return path + fileName;
    }


    @PostMapping("/category")
    public String category() {
        return "category";
    }

    @GetMapping("/AeroSense")
    @ResponseBody
    public String aeroSense(@RequestBody String data, HttpServletResponse httpServletResponse) {

        System.out.println("getContentType：" + httpServletResponse.getContentType());
        System.out.println("getCharacterEncoding：" + httpServletResponse.getCharacterEncoding());
        System.out.println("getStatus：" + httpServletResponse.getStatus());

        Collection<String> headerNames = httpServletResponse.getHeaderNames();
        for (String headerName : headerNames) {
            System.out.println(headerName + ":" + httpServletResponse.getHeader(headerName));
        }

        System.out.println(data);
        if (data.indexOf("KeepAlive") != -1 || data.indexOf("FallDetect") != -1) {
            System.out.println("OK");
            return "OK";
        } else {
            System.out.println("Error");
            return "Error";
        }
    }

    @PostMapping("/AeroSense")
    @ResponseBody
    public String aeroSenses(@RequestBody String data, HttpServletResponse httpServletResponse) {

        System.out.println("getContentType：" + httpServletResponse.getContentType());
        System.out.println("getCharacterEncoding：" + httpServletResponse.getCharacterEncoding());
        System.out.println("getStatus：" + httpServletResponse.getStatus());

        Collection<String> headerNames = httpServletResponse.getHeaderNames();
        for (String headerName : headerNames) {
            System.out.println(headerName + ":" + httpServletResponse.getHeader(headerName));
        }

        System.out.println(data);
        if (data.indexOf("KeepAlive") != -1 || data.indexOf("FallDetect") != -1) {
            System.out.println("OK");
            return "OK";
        } else {
            System.out.println("Error");
            return "Error";
        }
    }
}
